package de.bbl.android.fragment.NewsCenter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import de.bbl.android.BBLAndroidFragmentActivity;
import de.bbl.android.R;
import de.bbl.android.activities.NewsExpandedActivity;
import de.bbl.android.adapter.NewsCenter.NewsArrayAdapter;
import de.bbl.android.classes.RssItem;
import de.bbl.android.tools.Tools;
import de.bbl.android.tools.XmlParseRssTools;

public class NewsCenterFragment extends ListFragment {
	boolean loadedData;
	Activity activity;
	RssItem[] currentLoaded = null;
	NewsArrayAdapter currentUsedAdapter = null;
	boolean mDualPane;
	int mCurCheckPosition = 0;
	boolean isDetached = false;
	
	@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isDetached = false;
        setHasOptionsMenu(true);
    	RefreshData();
        
        View newsExpanded = getActivity().findViewById(R.id.fragment_side_content);
        mDualPane = newsExpanded != null && newsExpanded.getVisibility() == View.VISIBLE;
        
        if (mDualPane) {
        	ListView lv = getListView();
        	// lv.setDivider(getActivity().getResources().getDrawable(android.R.color.black));
        	// lv.setDividerHeight(2);
        	lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        	if (currentLoaded != null)
            	showNewsExpanded(mCurCheckPosition);
        }
    }
	
	private void loadData(String contextData) {
    	if (Tools.isSdPresent()){
			String[] dataArrayUrl = getResources().getStringArray(R.array.Data_Files_Url);
			String[] dataArray = getResources().getStringArray(R.array.Data_Files);
			String dataUrl = "";
			String data = "";
			boolean magazin = false;
			
			if (contextData.toLowerCase().equals("magazin")) {
				dataUrl = dataArrayUrl[BBLAndroidFragmentActivity.DATA_MAGAZIN];
				data = dataArray[BBLAndroidFragmentActivity.DATA_MAGAZIN];
				magazin = true;
			} else {
				return;
			}

			if (magazin)
				loadedData = Tools.getMagazinData(getResources().getString(R.string.main_url_magazin), dataUrl, data, BBLAndroidFragmentActivity.bbl_temp_sd_path);
		}
	}

    private void startProgress(String fileToLoad, View view) {
    	final String tempLoad = fileToLoad;
    	final Handler refresh = new Handler(Looper.getMainLooper());
    	Runnable runnable = new Runnable() {			
			public void run() {
				loadData(tempLoad);
				if (loadedData) 
		    		currentLoaded = XmlParseRssTools.XmlParseRss(BBLAndroidFragmentActivity.bbl_temp_sd_path + "magazin", BBLAndroidFragmentActivity.bbl_temp_img_sd_path);

		    	refresh.post(new Runnable() {
					public void run() {
						if (loadedData && ! isDetached()) {							
							representNewsData(tempLoad);
						}
					}
				});				
			}
		};		
		new Thread(runnable).start();
    }
    
    private void representNewsData(String filename) {
    	final boolean currentDualPane = mDualPane;
    	
    	if (loadedData) {							
    		ArrayList<RssItem> arrayList = new ArrayList<RssItem>();
			if ((currentLoaded != null))
			{
				for (int i = 0; i < currentLoaded.length; i++) {
					arrayList.add(currentLoaded[i]);
				}
				
				Collections.sort(arrayList, new Comparator<RssItem>() {
					   public int compare(RssItem o1, RssItem o2) {
					      Date a = o1.getPubDate();
					      Date b = o2.getPubDate();
					      if (a.before(b)) 
					        return -1;
					      else if (a.equals(b)) // it's equals
					         return -1;
					      else
					         return 1;
					   }
					});
				
				Collections.reverse(arrayList);
			}
			currentLoaded = arrayList.toArray(new RssItem[0]);			
    		AsyncTask<Void, Void, NewsArrayAdapter> task = new AsyncTask<Void, Void, NewsArrayAdapter>() {
    			@Override
		        protected NewsArrayAdapter doInBackground(Void... params) {
    				NewsArrayAdapter adapter = new NewsArrayAdapter(activity, currentLoaded);
		            return adapter;
		        }
    			
		        @Override
		        protected void onPostExecute(NewsArrayAdapter adapter) {
		    		currentUsedAdapter = adapter;
		            setListAdapter(currentUsedAdapter);
		            if (currentDualPane && !isDetached())
		            	showNewsExpanded(mCurCheckPosition);
		        }
    		};
    		task.execute();
    		// NewsArrayAdapter listAdapter = new NewsArrayAdapter(activity, currentLoaded);
    		// currentUsedAdapter = listAdapter;
        	// setListAdapter(listAdapter);
    	} else {
    		setListAdapter(null);	
    	}
    }
    
    private void showNewsExpanded(int currentPos) {
    	mCurCheckPosition = currentPos;
    	
    	if (mDualPane && ! isDetached) {
    		getListView().setItemChecked(currentPos, true);

    		// NewsCenterExtendedFragment extended = (NewsCenterExtendedFragment) getFragmentManager().findFragmentById(R.id.fragment_side_content);
    		NewsCenterExtendedFragment extended = (NewsCenterExtendedFragment) getFragmentManager().findFragmentByTag("newscenter-extended");
    		if (extended == null || extended.getShownIndex() != currentPos || ! extended.isVisible() ) {
    			extended = NewsCenterExtendedFragment.newInstance(currentPos, currentLoaded[currentPos]);
    			FragmentTransaction ft = getFragmentManager().beginTransaction();
    			ft.replace(R.id.fragment_side_content, extended, "newscenter-extended");
    			ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    			ft.commit();
    		}
    	} else if (! isDetached){
    		Intent intent = new Intent();
    		intent.setClass(getActivity(), NewsExpandedActivity.class);
    		 intent.putExtra("index", currentPos);
            RssItem feed = currentLoaded[currentPos];
            Bundle b = new Bundle();
            b.putString("title", feed.getTitle());
            b.putString("description", feed.getDescription());
            b.putString("link", feed.getLink());
            b.putString("pubdate", feed.getDate());
            b.putStringArray("pics", feed.getImagePath());
            intent.putExtra("android.intent.extra.INTENT", b);
            startActivity(intent);
    	}
    }
	
    @Override
	public void onListItemClick(ListView l, View v, int position, long id) {
    	showNewsExpanded(position);
    }

    /*
    @Override
	public void onListItemClick(ListView l, View v, int position, long id) {
    	// waiting for backgroundprocesses, very dirty
    	while (! currentUsedAdapter.isFinished()) {
    		;
		}
    	
    	Intent intent = new Intent();
        intent.setClass(getActivity(), NewsExpandedActivity.class);
        RssItem feed = currentLoaded[position];
        Bundle b = new Bundle();
        b.putString("title", feed.getTitle());
        b.putString("description", feed.getDescription());
        b.putString("link", feed.getLink());
        b.putString("pubdate", feed.getDate());
        b.putStringArray("pics", feed.getImagePath());
        intent.putExtra("android.intent.extra.INTENT", b);
        startActivity(intent);
	}
	*/
 
    @Override
    public void onDestroyView() {
    	isDetached = true;
    	super.onDestroyView();
    }
    
    public void RefreshData() {
        activity = getActivity();
        if (activity != null) {
    		startProgress("magazin", activity.getCurrentFocus());
        }
    }

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// super.onCreateOptionsMenu(menu, inflater);
    	inflater.inflate(R.menu.activity_bblmain_refresh, menu);
    	
    	// remove Refresh from OptionsMenu cause is implemented in titlebar
    	if (android.os.Build.VERSION.SDK_INT < 11)
    		menu.getItem(0).setVisible(false);
	}
	
	@Override
	public void onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
	}

    @Override    
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.Refresh:
            	RefreshData();
            	break;
        }
        return true;
    }
	
    @Override
	public void onDetach() {
    	isDetached = true;
		super.onDetach();
	}

	@Override
	public void onAttach(Activity activity) {
		isDetached = false;
		super.onAttach(activity);
	}

    
}
